package controller

import (
	"encoding/json"
	"go-crud-demo/model"
	"net/http"
	"regexp"
)

type Student struct {
	Id   float64 `json:"id"`
	Name string  `json:"name"`
}

func registerStudentRouters() {
	http.HandleFunc("/students", listStudent)
	http.HandleFunc("/students/add", addStudent)
	http.HandleFunc("/students/edit", editStudent)
	http.HandleFunc("/students/delete/", deleteStudent)
}

func listStudent(w http.ResponseWriter, r *http.Request) {
	students, err := model.GetAllStudents()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte(err.Error()))
	} else {
		enc := json.NewEncoder(w)
		err := enc.Encode(students)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte(err.Error()))
		}
	}
}
func addStudent(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodPost {
		dec := json.NewDecoder(r.Body)
		s := model.Student{}
		err := dec.Decode(&s)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte(err.Error()))
		} else {
			err = s.Insert()
			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte(err.Error()))
			} else {
				http.Redirect(w, r, "/students", http.StatusSeeOther)
			}
		}
	}
}
func editStudent(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodPost {
		dec := json.NewDecoder(r.Body)
		s := model.Student{}
		err := dec.Decode(&s)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte(err.Error()))
		} else {
			err = s.EditStudent()
			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte(err.Error()))
			}
		}
	}
}
func deleteStudent(w http.ResponseWriter, r *http.Request) {
	idPattern := regexp.MustCompile(`/students/delete/([0-9]*$)`)
	matches := idPattern.FindStringSubmatch(r.URL.Path)

	if len(matches) > 0 {
		id := matches[1]

		if r.Method == http.MethodDelete {
			err := model.DeleteStudent(id)

			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte(err.Error()))
				return
			}
			http.Redirect(w, r, "/students", http.StatusSeeOther)
			return
		}
	}

	w.WriteHeader(http.StatusNotFound)
}
